package com.common.utils;


import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.common.constant.SharesConstan;
import com.common.constant.UpLoadConstant;
import com.entity.HintShares;
import com.entity.SharesInform;
import org.springframework.util.CollectionUtils;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 阿里云操作工具类
 */
public class AliyunUtils {


    private static  OSS oss=new OSSClientBuilder().build(UpLoadConstant.ENDPOINT, UpLoadConstant.ACCESSKEYID , UpLoadConstant.ACCESSKEYSECRET);;
    /**
     * 获取上传驱动
     * @return
     */
    public static OSS getOos(){
        return  oss;
    }

    /**
     * 上传图片
     * @param name
     * @param code
     * @param type
     */
    public static void UploadImg(String name, String code, String type) {
        String img="";
        //提醒插入数据库
        OSS ossClient = null;
            try {
                String imgcode = code.contains("sz")?( "0." + code.substring(2)):(  "1." + code.substring(2));
                // 创建OSSClient实例。
                ossClient = getOos();
                if(SharesConstan.FS.equals(type)){
                    img = MeUtils.imgBase64( "http://webquotepic.eastmoney.com/GetPic.aspx?nid=" + imgcode + "&imageType=r");
                }
                if(SharesConstan.DAY.equals(type)){
                    img = MeUtils.imgBase64( "http://webquoteklinepic.eastmoney.com/GetPic.aspx?nid="+imgcode+"&UnitWidth=-6&imageType=KXL&EF=&Formula=RSI&AT=1&&type=");
                }
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] file = decoder.decodeBuffer(img);
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentLength(file.length);
                InputStream input = new ByteArrayInputStream(file);
                ossClient.putObject(UpLoadConstant.BUCKETNAME, name, input, objectMeta);
            }catch (Exception e){
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        //钉钉机器人地址（配置机器人的webhook）
        String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=26bef694851730b4480524fa4f95ac913f40eeeb9975bef184df5cb5682e9f83";
        //是否通知所有人
        boolean isAtAll = true;
        //通知具体人的手机号码列表
        List<String> mobileList = new ArrayList<>();
        mobileList.add("18285152065");
        //组装请求内容
        List<HintShares> hintSharesList=new ArrayList<>();
        HintShares hintShares=new HintShares()  ;
        hintShares.setCode("sz300086");
        hintShares.setName("康芝药业");
        hintSharesList.add(hintShares);
        String reqStr = buildReqStr(hintSharesList, isAtAll, mobileList,"测试");
        //推送消息（http请求）
        String result = HttpUtil.postJson(dingUrl, reqStr);
        System.out.println("result == " + result);
    }

    private static String buildReqStr(List<HintShares> hintShares, boolean isAtAll, List<String> mobileList, String title) {


        StringBuffer sb=new StringBuffer();
        List<SharesInform> sharesInforms=new ArrayList<>();
        for (HintShares vo : hintShares) {

            String zsf= "sh/"+vo.getCode()+"_f_"+DateUtil.getLongByCurrTime()+".jpg";;
            String zsr= "sh/"+vo.getCode()+"_r_"+DateUtil.getLongByCurrTime()+".jpg";;

            //上传图片
            AliyunUtils.UploadImg(zsf,vo.getCode(),SharesConstan.FS);
            AliyunUtils.UploadImg(zsr,vo.getCode(),SharesConstan.DAY);
           // http://124.220.197.73:9200/shares
            sb.append(title+"_"+"["+vo.getName()+"](http://124.220.197.73:9200/shares?id_code="+vo.getCode()+")"+"_排序_"+vo.getAsorder()
                    +"\n"+ "![]("+"https://andi159753.oss-cn-hangzhou.aliyuncs.com/"+zsf+")"+"\n"
                    +"![]("+"https://andi159753.oss-cn-hangzhou.aliyuncs.com/"+zsr+")"+"\n" );


            List<String> voList=new ArrayList<>();
            voList.add(zsf);
            voList.add(zsr);
            for (String name : voList) {
                SharesInform sharesInform = new SharesInform();
                sharesInform.setName(vo.getName());
                sharesInform.setCode(vo.getCode());
                sharesInform.setPath(name);
                sharesInform.setTime(DateUtil.DEFAULT_DATE_FORMAT.format(new Date()));
                sharesInform.setType(title);
                sharesInforms.add(sharesInform);
            }
        }
        Map<String, Object> atMap =new HashMap<>();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "markdown");
        Map<String,Object> pmap=new HashMap<>();
        pmap.put("text", sb.toString());
        pmap.put("title","####<"+title);
        reqMap.put("markdown", pmap);

        return JSON.toJSONString(reqMap);
    }
}
